package cn.lianyutiantang.utils.safety;



import cn.lianyutiantang.model.YnSystemLog;
import cn.lianyutiantang.service.user.LogService;
import cn.lianyutiantang.utils.CusAccessObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 日志拦截接口--本来想做成自定义标签的发现不成功改成试下这个
 * Created by zjl on 2017/6/26.
 */
//public class SystemLogInteceptor implements HandlerInterceptor {
    public class SystemLogInteceptor extends HandlerInterceptorAdapter {
//    @Value("#{commonInfo['isOpenSystemLog']}")
//    private boolean isOpenSystemLog;// 判断是否开启系统日志 true开始日志，false不开启系统日志
    @Autowired
LogService logService;


    // preHandle()方法在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
       /* if(!isOpenSystemLog){
            return true;
        }*/
        YnSystemLog ynSystemLogEntity=new YnSystemLog();
        String userId=null;
        String params=null;
        ynSystemLogEntity.setLastUpdatedBy(null);
        ynSystemLogEntity.setLoginName(null);
        ynSystemLogEntity.setUserName(null);
        ynSystemLogEntity.setUserId(userId);
        if(userId!=null&&!userId.equals("")){
            ynSystemLogEntity.setCreatedBy(Long.parseLong(userId));
        }
        ynSystemLogEntity.setCreatedDate(new Date());
        ynSystemLogEntity.setHostName(request.getRemoteHost());
        ynSystemLogEntity.setIp(CusAccessObjectUtil.getIpAddress(request));
        ynSystemLogEntity.setRequestMethod(request.getMethod());
        ynSystemLogEntity.setServletPath(request.getRequestURL().toString());
        ynSystemLogEntity.setUrl(request.getRequestURI());

        /*System.out.println("request.getRequestURL():" + request.getRequestURL());
        System.out.println("request.getServletPath():" + request.getServletPath());
        System.out.println("request.getParameter(userName):" + request.getParameter("userName"));
        System.out.println("request.getAttribute(userName):" + request.getAttribute("userName"));
        System.out.println(appLoginUser);
        System.out.println("preHandle");
        System.out.println(request.getRequestURL());//得到请求URL地址
        System.out.println(request.getRequestURI());//得到请求的资源
        System.out.println(request.getQueryString());
        System.out.println(request.getRemoteAddr());//得到来访者IP
        System.out.println(request.getRemoteHost());
        System.out.println(request.getRemotePort());//得到请求的资源
        System.out.println(request.getMethod());//得到请求的资源*/
        if (o instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod) o;
            ynSystemLogEntity.setControllerName(h.getBean().getClass().getName());
            ynSystemLogEntity.setFunctionName(h.getMethod().getName());
           /* StringBuilder sb = new StringBuilder(1000);
            sb.append("-----------------------").append(new SimpleDateFormat("yyyy-mm-dd").format(new Date()))
                    .append("-------------------------------------\n");

            sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
            sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
            sb.append("Params    : ").append(getParamString(request.getParameterMap())).append("\n");
            sb.append("URI       : ").append(request.getRequestURI()).append("\n");
            System.out.println(sb.toString());*/
        }

       /* BodyReaderHttpServletRequestWrapper myRequestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
        String body = myRequestWrapper.getBody();
        String clientIP = myRequestWrapper.getRemoteHost();
        int clientPort = request.getRemotePort();
        String uri = myRequestWrapper.getRequestURI();
        System.out.println(body);
        System.out.println(clientIP);
        System.out.println(clientPort);
        System.out.println(uri);*/
      //  return super.preHandle(request, response, o);
        String requestMethod=request.getMethod();
        if(requestMethod.toUpperCase().equals("GET")){
            ynSystemLogEntity.setParams(null);
        }else if(requestMethod.toUpperCase().equals("POST")){
            ynSystemLogEntity.setParams(null);
        }
        logService.createLog(ynSystemLogEntity);
        return true;
    }


    // postHandle()方法在业务处理器处理请求之后被调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
//        LoginAppDTO appLoginUser = (LoginAppDTO) request.getAttribute("appLoginUser");//获取app登录用户信息
//        System.out.println("request.getRequestURL():" + request.getRequestURL());
//        System.out.println("request.getServletPath():" + request.getServletPath());
//        System.out.println("request.username():" + request.getParameter("userName"));
//        System.out.println(appLoginUser);
//        System.out.println("postHandle");
//        System.out.println(request.getRequestURL());//得到请求URL地址
//        System.out.println(request.getRequestURI());//得到请求的资源
//        System.out.println(request.getQueryString());
//        System.out.println(request.getRemoteAddr());//得到来访者IP
//        System.out.println(request.getRemoteHost());
//        System.out.println(request.getRemotePort());//得到请求的资源
//        System.out.println(request.getMethod());//得到请求的资源
        super.postHandle(request, response, o, modelAndView);
    }

    // afterCompletion()方法在DispatcherServlet完全处理完请求后被调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
//        LoginAppDTO appLoginUser = (LoginAppDTO) request.getAttribute("appLoginUser");//获取app登录用户信息
//        System.out.println("request.getRequestURL():" + request.getRequestURL());
//        System.out.println("request.getServletPath():" + request.getServletPath());
//        System.out.println("request.username():" + request.getParameter("userName"));
//        System.out.println(appLoginUser);
//        System.out.println("afterCompletion");
//        System.out.println(request.getRequestURL());//得到请求URL地址
//        System.out.println(request.getRequestURI());//得到请求的资源
//        System.out.println(request.getQueryString());
//        System.out.println(request.getRemoteAddr());//得到来访者IP
//        System.out.println(request.getRemoteHost());
//        System.out.println(request.getRemotePort());//得到请求的资源
//        System.out.println(request.getMethod());//得到请求的资源
        super.afterCompletion(request, response, o, e);
    }

}
